package com.jnu.weather.service;

import com.jnu.weather.domain.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WeatherServiceImpl implements WeatherService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RestTemplate restTemplate;

    @Override
    public WeatherResponse weatherApi(String cityid,String city){
       WeatherResponse redisWeatherResponse =(WeatherResponse) redisTemplate.opsForHash().get("weatherdata",city);
       if(redisWeatherResponse==null){
           synchronized (this){
               WeatherResponse echoRedisWeatherResponse =(WeatherResponse) redisTemplate.opsForHash().get("weatherdata",city);
               if(echoRedisWeatherResponse==null){
                   System.out.println("查询接口");
                   WeatherResponse weatherResponse =restTemplate.getForObject("https://apis.tianapi.com/tianqi/index?key="+"36a4e4dd1fb131c22b281b4814ac212e"+"&city="+cityid+"&type=1", WeatherResponse.class);
                   redisTemplate.opsForHash().put("weatherdata",city,weatherResponse);
                   return weatherResponse;
               }
               else{
                   System.out.println("查询缓存");
                   return echoRedisWeatherResponse;
               }

           }

       }else {
           System.out.println("查询缓存");
           return redisWeatherResponse;
       }
    }

    @Override
    public void cacheWeatherData(String cityid,String city) {
        WeatherResponse weatherResponse=weatherApi(cityid,city);
        System.out.println(weatherResponse.getResult().getWeather());
        redisTemplate.opsForHash().put("weatherdata",city,weatherResponse);
    }
}
